<?php
/**
 * 首页控制器
 */
class IndexController extends Controller{
    /**
	 * 
	 */
    public function index(){
    	//分类数据处理
        $cateData = K('Cate')->where("pid=0")->all();
		foreach ($cateData as $k => $v) {
			//找到子集，重新压入数组
			$cateData[$k]['son'] = K('Cate')->where("pid={$v['cid']}")->all();
			
		}
		$this->assign('cateData',$cateData);
		
		//轮播图数据处理
		$bannerData = K('Banner')->all();
		$this->assign('bannerData',$bannerData);
		
		//品牌数据处理
		$brandData = K('Brand')->all();
		$this->assign('brandData',$brandData);
		
		//商品数据处理
		$goodsData = K('Goods')->all();
		$this->assign('goodsData',$goodsData);
		
		
		//第一层楼衣服数据
		$cateAll = K('Cate')->all();
		//1.根据当前分类的cid,获得所有的子集cid
		$sonCids = $this->_getSonCid($cateAll,1);
		if(!$sonCids){
			$Clothes = array();
		}else{
			//2.根据cid获得所有的商品gid
			$Clothes = M()->join('__goods__ g JOIN __brand__ b ON b.bid=g.brand_bid')->where('category_cid in(' . implode(',', $sonCids) . ')')->order("addtime")->all();
		}
		$ClothesNum = count($Clothes);
		$this->assign('ClothesNum',$ClothesNum);
		$this->assign('Clothes',$Clothes);
		
		//第二层楼母婴数据
		$sonCids = $this->_getSonCid($cateAll,2);
		if(!$sonCids){
			$moAndba = array();
		}else{
			$moAndba = M()->join('__goods__ g JOIN __brand__ b ON b.bid=g.brand_bid')->where('category_cid in(' . implode(',', $sonCids) . ')')->all();
		}
		$moAndbaNum = count($moAndba);
		$this->assign('moAndbaNum',$moAndbaNum);
		$this->assign('moAndba',$moAndba);
		
		//第三层楼居家数据
		$sonCids = $this->_getSonCid($cateAll,3);
		if(!$sonCids){
			$Family = array();
		}else{
			$Family = M()->join('__goods__ g JOIN __brand__ b ON b.bid=g.brand_bid')->where('category_cid in(' . implode(',', $sonCids) . ')')->all();
		}
		$FamilyNum = count($Family);
		$this->assign('FamilyNum',$FamilyNum);
		$this->assign('Family',$Family);		
		
		//今日商品处理
		$todayData = K('Goods')->order("addtime")->all();
		$this->assign('todayData',$todayData);
		
		
		$this->display();
	}
		
		
	/**
	 * 获得当前分类所对应所有的子集cid
	 */
	private function _getSonCid($cateData,$cid){
		$temp = array();
		foreach ($cateData as $cate) {
			if($cate['pid'] == $cid){
				$temp[] = $cate['cid'];
				$temp = array_merge($temp,$this->_getSonCid($cateData, $cate['cid']));
			}
		}
		return $temp;
	}
	
	/**
	 * 退出
	 */
	public function out(){
	    session(NULL);
		$this->success('退出成功',U('Login/index'));
	}
	
	
}
